<?php

namespace app\common\logic;

use app\common\configs\CommonData;
use app\common\model\commonModel;
use app\common\model\trCache;
use app\common\model\trDriver;
use app\common\model\trBusesLine;
use app\common\model\trOrder;
use app\common\util\Tools;
use app\common\util\WxPay;
use think\Db;

/**
 * Class Sms
 * 司机逻辑类
 * @package Admin\Controller
 */
class DriverLogic
{
    public static function getSn(){
        return date('YmdHis') . rand(1000, 9999);
    }

    // 定时处理订单 分佣
    // status 1待支付，2已支付，3已取消；4待分配；5已分配；6司机拒接；7司机已接单；8已完成；9已退款；10待退款；11部分退款
    // 类型；1机场接送，2巴士线路，3专车接送，4包车线路
    public function getHandleOrderCommission(){ // 包车线路没有分佣概念
        $orderModel = new trOrder();
        //获取固定线路的佣金分配
        $where = Db::raw("`settlement` = '0' and (`status` = 2 or `status` = 8) and `type` = 2 and reserve_time < '" .date("Y-m-d H:i:s")."'");
        $orderData = $orderModel->getFields("id,order_sn,line_id,commission,mall_id", $where, false, false);
        if(count($orderData)){
            $busesModel = new trBusesLine(); // 巴士线路
            $orderId = [];
            foreach ($orderData as $item){
                $item = Tools::transferFields($item->getData());
                $error = 0;
                if($item["commission"]) {
                    if (empty($lineData[$item["lineId"]])) {
                        $lineData[$item["lineId"]] = $busesModel->getFields("driver", ["id" => $item["lineId"]]);
                    }
                    if (!empty($lineData[$item["lineId"]]["driver"])) {
                        $driverIds = explode(",", $lineData[$item["lineId"]]["driver"]);
                        $commission = number_format($item["commission"] / count($driverIds),2,'.','');
                        $insert = ["order_sn" => $item["orderSn"], "money" => $commission, "type" => 2, "pay_time" => time(), "mall_id" => $item["mallId"]];
                        $driverModel = new trDriver();
                        foreach ($driverIds as $id){
                            $insert["driver_id"] = $id;
                            $res = commonModel::toAdd(orderCommissionTable, $insert);
                            if(isset($res["code"])) {
                                $error = 1;
                                Tools::writeLog("线路分佣错误：数据为：".var_export($insert,1). "-----订单数据".var_export($item,1). "-----报错".var_export($res,1), "commission_error.txt");
                                break;
                            }else{
                                $driverModel->where(["id" => $id])->update(["balance" => Db::raw("balance+".$commission)]);
                            }
                        }
                    }
                }
                if(!$error){
                    $orderId[] = $item["id"];
                }
            }
            if($orderId) {
                $orderModel->doUpdate(["settlement" => "1", "status" => 8], [["id", "in", $orderId]]); // 设为已结算
            }
        }

        // 新包车线路，不需要分佣，直接设为已结算
        Db::name($orderModel->getName())->where([["settlement", "=", "0"], ["status", "=", 2], ["type", "=", 4], ["reserve_time", "<", date("Y-m-d H:i:s")]])->update(["settlement" => "1", "status" => 8]);

        $where = Db::raw("`settlement` = '0' and `status` = 8 and type <> 2");
        $orderData = $orderModel->getFields("id,order_sn,line_id,commission,type,status,allot_driver_id,mall_id", $where, false, false);
        if(count($orderData)){
            $driverModel = new trDriver();
            $orderId = [];
            foreach ($orderData as $item){
                $item = Tools::transferFields($item->getData());
                $error = 0;
                if($item["commission"] && !commonModel::getCount(orderCommissionTable, ["order_sn" => $item["orderSn"], "driver_id" => $item["allotDriverId"]])) {
                    $res = commonModel::toAdd(orderCommissionTable, [
                        "order_sn" => $item["orderSn"], "money" => $item["commission"], "type" => $item["type"], "pay_time" => time(),
                        "driver_id" => $item["allotDriverId"], "mall_id" => $item["mallId"]
                    ]);
                    if (isset($res["code"])) {
                        $error = 1;
                        Tools::writeLog("11线路分佣错误：result：" . $res . "-----" . var_export($item, 1) . "-----报错：" . var_export($res, 1), "commission_error.txt");
                    } else {
                        $driverModel->where(["id" => $item["allotDriverId"]])->update(["balance" => Db::raw("balance+" . $item["commission"])]);
                    }
                }
                if(!$error){
                    $orderId[] = $item["id"];
                }
            }
            if($orderId) {
                Db::name($orderModel->getName())->where("id", "in", implode(",", $orderId))->update(["settlement" => 1]);
            }
        }
        request()->mallData = ["id" => 0]; // 重置商城ID
        trCache::saveCache(["key" => CommonData::COMMISSION_JAVASCRIPT, "value" => [
            "name" => CommonData::$javascriptList[CommonData::COMMISSION_JAVASCRIPT], "aliasName" => CommonData::COMMISSION_JAVASCRIPT,
            'execTime' => date("Y-m-d H:i:s")
        ]]);
    }

    public static function getHandleTransfer($openid, $money){
        $transferSn = self::getSn();
        $transferData = [
            "total_fee" => $money,
            "out_trade_no" => $transferSn,
            "openid" => $openid
        ];
        $wx = new WxPay();
        $result = $wx->transfer($transferData);
        if($result['code'] > 0){
            return [
                "transfer_sn" => $result['response']['out_biz_no'],
                "trade_no" => $result['response']['order_id'],
                "complete_time" => time()
            ];
        }else{
            return $result;
        }
    }
}